package com.itheima.demo;

import com.itheima.domain.User;
import com.itheima.mapper.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/*
    持久层测试类
 */
public class Demo01 {

    @Test
    //测试打印数据库中所有对象
    public void testFindAll() throws IOException {
        //读取核心配置文件
        InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
        //构造工厂对象
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
        //获取SqlSession对象  传参true 代表自动提交事务  后面可省去commit
        SqlSession sqlSession = factory.openSession(true);
        //通过sqlSession获取接口的代理对象
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //调用接口中方法
        List<User> users = mapper.selectAll();
        System.out.println(users);
        //事务提交
//        sqlSession.commit();
        //释放资源
        sqlSession.close();
        is.close();

    }

    //通过email查找用户
    @Test
    public void findByEmail() throws IOException {
        //读取核心配置文件
        InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
        //构建工厂对象
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
        //获取sqlsession对象
        SqlSession sqlSession = factory.openSession();
        //通过session获取接口的代理对象
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //调用接口中的方法
        List<User> users = mapper.findByEmail("");
        System.out.println(users);
        //提交事务
        sqlSession.commit();
        //释放资源
        sqlSession.close();
        is.close();
    }


    //通过数组查找 或 无条件则全搜索
    @Test
    public void findByNames() throws IOException {
        //读取核心配置文件
        InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
        //获取工厂对象
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
        //获取sqlsession
        SqlSession sqlSession = factory.openSession(true);
        //通过sqlSession获取接口代理的对象
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //通过接口代理对象调用方法
        String[] names = {"aunero","yuki"};
//        List<User> users = mapper.findByNames(null);
        List<User> users = mapper.findByNames(names);
        System.out.println(users);
        //释放资源
        sqlSession.close();
        is.close();
    }
}
